package com.itheima.common.utils;


import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class RequestContext {

    /**
     * RequestContextHolder：获取当前请求中的封装对象信息
     *      请求信息 httpServletRequest
     *      相应信息 httpServletResponse
     *      会话信息 httpSession
     */
    public static String getNode(String key){
        /**
         * 获取httpServletRequest
         * 获取请求头信息
         */

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();
        return request.getHeader(key);
    }
    /**
     * 获取指定token
     */
    public static String getToken(){
        return getNode("token");
    }
    /**
     * token转为map
     */
    public static Map<String,Object> tokenMap(){
        String token = getNode("token");
        return JwtUtils.parse(token);
    }
    /**
     * 获取token中指定key的数据
     */
    public static <T> T getNodeValue(String key){
        return (T)tokenMap().get(key);
    }

    /***
     * 获取response
     */
    public static HttpServletResponse getResponse(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getResponse();
    }


    /***
     * 获取request
     */
    public static HttpServletRequest getRequest(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getRequest();
    }


}
